<template>
  <div class="container">
    <div class="app-container">
      <!-- 添加按钮 -->
      <el-button type="primary" @click="showDialog=true">添加角色</el-button>
      <!-- 表格 -->
      <el-table
        :data="list"
        style="width: 100%"
      >
        <el-table-column
          align="center"
          prop="name"
          label="角色"
          width="180"
        >
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" placeholder="" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="state"
          label="启用"
          width="180"
        >
          <!-- 插槽 -->
          <template v-slot="{row}">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state===1?'已启用':'未启用' }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="description"
          label="描述"
        >
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" placeholder="" size="mini" type="textarea" :rows="3" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="操作"
        >
          <template v-slot="{row}">
            <template v-if="row.isEdit">
              <el-button type="primary" size="mini" @click="btnEditOk(row)">确认</el-button>
              <el-button size="mini" @click="btnEditCancel(row)">取消</el-button>
            </template>

            <template v-else>
              <el-button type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button type="text" @click="btnEdit(row)">编辑</el-button>
              <el-popconfirm
                title="确定删除该角色？"
                @onConfirm="delRole(row.id)"
              >
                <el-button slot="reference" type="text">删除</el-button>
              </el-popconfirm>
            </template>

          </template>
        </el-table-column>

      </el-table>
      <!-- 分页器 -->
      <el-row type="flex" style="height:60px" justify="end" align="middle">
        <el-pagination
          layout="prev, pager, next"
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          @current-change="changePage"
        />
      </el-row>
      <!-- 弹窗 -->
      <el-dialog
        title="新增角色"
        :visible.sync="showDialog"
        width="width"
        @close="btnCancel"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="80px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="启用" prop="state">
            <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" type="textarea" :rows="3" />
          </el-form-item>
          <el-row type="flex" justify="center">
            <el-form-item>
              <el-button type="primary" @click="btnOk">确认</el-button>
              <el-button @click="btnCancel">取消</el-button>
            </el-form-item>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
    <el-dialog
      title="分配权限"
      :visible.sync="showPermDialog"
    >
      <el-tree
        ref="permTree"
        node-key="id"
        :data="treeData"
        :props="{label:'name'}"
        show-checkbox
        default-expand-all
        :default-checked-keys="permIds"
        check-strictly
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
          <el-button size="mini" @click="showPermDialog = false">取消</el-button>
        </el-col>
      </el-row>

    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, addRole, delRole, updateRole, getRoleDetail, assignPerm } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { transListToTreeData } from '@/utils'
export default {
  data() {
    return {
      showPermDialog: false,
      showDialog: false,
      treeData: [],
      list: [],
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页多少条
        total: 0
      },
      roleForm: {
        name: '',
        description: '',
        state: 0
      },
      rules: { name: [{ required: true, trigger: 'blur', message: '角色名称不能为空' }],
        description: [{ required: true, trigger: 'blur', message: '角色描述不能为空' }]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      // console.log(await getRoleList())
      this.list = rows
      // 添加属性 控制显示模式  响应式
      this.list.forEach(item => { this.$set(item, 'isEdit', false) })
      this.list.forEach(item => {
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
      this.pageParams.total = total
    },

    changePage(newPage) {
      // newPage怎么来的
      this.pageParams.page = newPage
      this.getRoleList()
    },
    btnCancel() {
      this.showDialog = false
      this.$refs.roleForm.resetFields()
    },
    btnOk() {
      this.$refs.roleForm.validate(async(isOk) => {
        if (isOk) {
          await addRole(this.roleForm)
          // 重新获取渲染
          await this.getRoleList()
          this.$message.success('添加角色成功')
          // this.showDialog = false
          // this.$refs.roleForm.resetfields()
          this.btnCancel()
        }
      })
    },
    async delRole(id) {
      await delRole(id)

      this.$message.success('删除成功')
      // 删除的如果是最后一个
      if (this.list.length === 1) this.pageParams.page--
      this.getRoleList()
    },
    btnEdit(row) {
      console.log(11)

      row.isEdit = true
      console.log(3)

      // 缓存
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    async btnEditOk(row) {
      if (row.editRow.name && row.editRow.description) {
        // 下一步操作
        await updateRole({ ...row.editRow, id: row.id })
        // 更新成功
        this.$message.success('更新角色成功')
        // 更新显示数据  退出编辑状态
        // row.name = row.editRow.name // eslint的一校验 误判
        // Object.assign(target, source)
        Object.assign(row, {
          ...row.editRow,
          isEdit: false // 退出编辑模式
        }) // 规避eslint的误判
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    btnEditCancel(row) {
      row.isEdit = false
    },
    async btnPermission(id) {
      this.currentId = id
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds // 数组
      this.treeData = transListToTreeData(await getPermissionList(), 0)
      this.showPermDialog = true
    },
    async  btnPermissionOK() {
      await assignPerm({
        id: this.currentId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showPermDialog = false
    }
  }
}
</script>
<style scoped>

</style>
